﻿using JiveMessenger.Common;
using JiveMessenger.User;
using JiveMessenger.Utilities;
using JiveMessenger.ViewModels;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.Graphics.Display;
using Windows.Storage.Pickers;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

namespace JiveMessenger.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class SettingsPage : BasicPage
    {
        //private NavigationHelper navigationHelper;


        public SettingsPage()
        {
            this.InitializeComponent();

            //this.navigationHelper = new NavigationHelper(this);
            //this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            //this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
        }




        ///// <summary>
        ///// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>.
        ///// </summary>
        //public NavigationHelper NavigationHelper
        //{
        //    get { return this.navigationHelper; }
        //}



        protected override void SaveState(SaveStateEventArgs e)
        {
            base.SaveState(e);
            e.PageState["SettingsPivotIndex"] = this.PropertiesPivot.SelectedIndex;

        }

        protected override void LoadState(LoadStateEventArgs e)
        {
            base.LoadState(e);
            if (e.PageState == null || e.PageState.Count == 0)
                return;
            ViewModelSettingsPage vm = (ViewModelSettingsPage)this.DataContext;
            vm.SelectedPivotItemIndex = (int)e.PageState["SettingsPivotIndex"];
        }

        protected override async void OnNavigatedFrom(NavigationEventArgs e)
        {
            DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;

            //string password = CredentialsManager.GetStoredPasswordForUser(AppSettings.Instance.UsernameSetting);
            //if (this.pwBoxPassword.Password != null && this.pwBoxPassword.Password != password)
            //{
            //    CredentialsManager.RemoveCredential(AppSettings.Instance.UsernameSetting);
            //    CredentialsManager.SaveCredential(AppSettings.Instance.UsernameSetting, this.pwBoxPassword.Password);
            //}

            //  this.Animate(1, 0, "Opacity", 100,0);
            base.OnNavigatedFrom(e);
            //Storyboard sb = this.Resources["ShowPageHeaderAnim"] as Storyboard;
            this.TextBoxPageHeader.Opacity = 0;
            //Task.Run(() =>
            //    {

            ViewModelSettingsPage vm = this.DataContext as ViewModelSettingsPage;
            vm.SaveSettingsToServer();
            vm.Cleanup();
            if (!(e.Content is LoginPage))
            {
                await Task.Delay(500);

                StatusBar.GetForCurrentView().ShowAsync();
            }
            //});
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait;
            StatusBar.GetForCurrentView().HideAsync();


            this.TextBoxPageHeader.Opacity = 0;
            this.MessagesContentControl.Visibility = Visibility.Collapsed;

            this.ContentPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.ContentPanel.Opacity = 0;
            this.PushSettingsPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.PushSettingsPanel.Opacity = 0;

            await Task.Delay(50);
            this.ContentPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
            this.ContentPanel.Animate(0, 1, "Opacity", 100, 0);
            await Task.Delay(50);
            this.PushSettingsPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
            this.PushSettingsPanel.Animate(0, 1, "Opacity", 100, 0);
            await Task.Delay(50);
            this.MessagesContentControl.Visibility = Visibility.Visible;

            ViewModelSettingsPage vm = (ViewModelSettingsPage)this.DataContext;
            vm.UpdateAvatarFromSettings();
            //this.TextBoxPageHeader.Opacity = 1;
           // Canvas.SetZIndex(this.TextBoxPageHeader, 10);
            await Task.Delay(650);
            Storyboard sb = this.Resources["ShowPageHeaderAnim"] as Storyboard;
            sb.Begin();
        }

        //private async void AddServerFlyout_Opened(object sender, object e)
        //{
        //    ((ViewModelSettingsPage)this.DataContext).IsAddServerPopupOpen = true;
        //    Flyout f = this.AddServerButton.Flyout as Flyout;
        //    Border border = f.Content as Border;
        //    StackPanel panel = border.Child as StackPanel;
        //    panel.Opacity = 0;

        //    await Task.Delay(300);
        //    panel.Animate(0, 1, "Opacity", 300, 0);
        //}

        //private void AddServerFlyout_Closed(object sender, object e)
        //{
        //    ((ViewModelSettingsPage)this.DataContext).IsAddServerPopupOpen = false;
        //    this.TextBoxAddServer.Text = "";

        //}

        private void BasicPage_Loaded(object sender, RoutedEventArgs e)
        {
            Window.Current.Activated += Current_Activated;
        }

        private void BasicPage_Unloaded(object sender, RoutedEventArgs e)
        {
            Window.Current.Activated -= Current_Activated;
        }

        async void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
        {
            if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
                this.TextBoxPageHeader.Opacity = 0;
            else
            {
                StatusBar.GetForCurrentView().HideAsync();
                await Task.Delay(800);
                Storyboard sb = this.Resources["ShowPageHeaderAnim"] as Storyboard;
                sb.Begin();
            }
        }

        ///// <summary>
        ///// Handle the returned files from file picker
        ///// This method is triggered by ContinuationManager based on ActivationKind
        ///// </summary>
        ///// <param name="args">File open picker continuation activation argment. It cantains the list of files user selected with file open picker </param>
        //public void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
        //{
        //    if (args.Files.Count > 0)
        //    {
        //        Debug.WriteLine("Picked photo: " + args.Files[0].Name);
        //    }
        //    else
        //    {
        //        Debug.WriteLine("Operation cancelled.");
        //    }
            
        //}

        //private void AddAvatarButton_Click(object sender, RoutedEventArgs e)
        //{
        //    FileOpenPicker openPicker = new FileOpenPicker();
        //    openPicker.ViewMode = PickerViewMode.Thumbnail;
        //    openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        //    openPicker.FileTypeFilter.Add(".jpg");
        //    openPicker.FileTypeFilter.Add(".jpeg");
        //    openPicker.FileTypeFilter.Add(".png");
        //    openPicker.FileTypeFilter.Add(".bmp");
        //    // Launch file open picker and caller app is suspended and may be terminated if required
        //    openPicker.PickSingleFileAndContinue();
        //}
    }
}
